package com.example.myxmpp.service;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.example.myxmpp.dbhelper.ContactOpenHelper;
import com.example.myxmpp.dbhelper.SmsOpenHelper;
import com.example.myxmpp.fragment.ContactsFragment;
import com.example.myxmpp.provider.ContactsProvider;
import com.example.myxmpp.provider.SmsProvider;
import com.example.myxmpp.utils.PinyinUtil;
import com.example.myxmpp.utils.ThreadUtils;

import org.apache.commons.lang3.StringUtils;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.chat2.IncomingChatMessageListener;
import org.jivesoftware.smack.chat2.OutgoingChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.roster.RosterEntry;
import org.jivesoftware.smack.roster.RosterListener;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.Jid;

import java.util.Collection;

public class IMService extends Service {

    //public static XMPPConnection conn;
    public static AbstractXMPPConnection conn;

    public static String mCurAccount;//前登陆用户jid

    private Roster roster;

    private MyRosterLisener rosterListener;

    public static ChatManager chatManager;
    private IncomingChatMessageListener incomingChatMessageListener;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

   public class MyBinder extends Binder{
        public IMService getService(){
            return IMService.this; //返回
        }
    }

    @Override
    public void onCreate() {
        Log.i("service","@@@@@@@@@@@@@@@@@@@Service onCreate@@@@@@@@@@@@@@@@@@@@@@@");
        //同步联系人

        //开启线程，同步花名册
        ThreadUtils.runInThread(new Runnable() {

            @Override
            public void run() {
                //需要连接对像
                //得到花名册对像
                //samck3.x 4.x
                if (conn ==null){
                    Log.i("roster","=======conn为空　return================");
                    return;
                }
                roster = Roster.getInstanceFor(conn);

                //得到所有的联系人
                Collection<RosterEntry> entries = roster.getEntries();

                //打印联系人
                for(RosterEntry entry :entries){
                    Log.i("roster","=======打印联系人======"+entry.toString()+"==========");
                    Log.i("roster","=======打印联系人======"+entry.getUser()+"==========");
                    Log.i("roster","=======打印联系人======"+entry.getType()+"==========");
                    Log.i("roster","=======打印联系人======"+entry.getName()+"==========");
                    Log.i("roster","=======打印联系人======"+entry.getGroups()+"==========");
                    Log.i("roster","=======打印联系人======================================");
                }

                //监听联系人的改变
                rosterListener = new MyRosterLisener();
                roster.addRosterListener(rosterListener);

                for(RosterEntry entry :entries){
                    saveOrUpdateEntry(entry);
                }



                //创建消息的管理者 注册监听

                //1.获取消息的管理者
                if (chatManager == null) {
                    chatManager = ChatManager.getInstanceFor(conn);
                    incomingChatMessageListener = new InChatMessageListener();
                    chatManager.addIncomingListener(incomingChatMessageListener);


                }

            }
        });



        super.onCreate();
    }



    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("service","@@@@@@@@@@@@@@@@@@@Service onStartCommand@@@@@@@@@@@@@@@@@@@@@@@");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.i("service","@@@@@@@@@@@@@@@@@@@Service onDestroy@@@@@@@@@@@@@@@@@@@@@@@");
        //移除rosterListener
        if(roster != null && rosterListener != null){
            roster.removeRosterListener(rosterListener);
        }

        if (chatManager != null) {
            chatManager.removeIncomingListener(incomingChatMessageListener);
        }

        if (conn !=null) conn.disconnect();

        super.onDestroy();
    }

    class MyRosterLisener implements RosterListener {

        @Override
        public void entriesAdded(Collection<Jid> addresses) {//联系人添加
            //对应更新数据库
            for(Jid address : addresses){

                RosterEntry entry = roster.getEntry((BareJid) address);
                //要么更新，要么插入
                saveOrUpdateEntry(entry);
            }
        }

        @Override
        public void entriesUpdated(Collection<Jid> addresses) {//联系修改了

            //对应更新数据库
            for(Jid address : addresses){

                RosterEntry entry = roster.getEntry((BareJid) address);
                //要么更新，要么插入
                saveOrUpdateEntry(entry);
            }
        }

        @Override
        public void entriesDeleted(Collection<Jid> addresses) {//联系人删除了
            //对应更新数据库
            for(Jid account : addresses){

                // RosterEntry entry = roster.getEntry((BareJid) address);
                //执行删除操作
                getContentResolver().delete(ContactsProvider.URI_CONTACT, ContactOpenHelper.ContactTable.ACCOUNT +"=?",
                        new String[]{String.valueOf(account)});
            }

        }

        @Override
        public void presenceChanged(Presence presence) {//联系人状态改变了

        }
    }

    private void saveOrUpdateEntry(RosterEntry entry) {
        ContentValues values = new ContentValues();

        String account = entry.getUser();
        // account = account.substring(0,account.indexOf("@")) + "@" + LoginActivity.SERVICENAME;

        String nickname = entry.getName();
        //处理昵称
        if (nickname == null || "".equals(nickname)){
            nickname = account.substring(0,account.indexOf("@"));
        }
        values.put(ContactOpenHelper.ContactTable.ACCOUNT,account);
        values.put(ContactOpenHelper.ContactTable.NICKNAME,nickname);
        values.put(ContactOpenHelper.ContactTable.AVATAR,"0");
        values.put(ContactOpenHelper.ContactTable.PINYIN, PinyinUtil.getPinyin(account));

        //update,后插入
        int updateConut = getContentResolver().update(ContactsProvider.URI_CONTACT,values,
                ContactOpenHelper.ContactTable.ACCOUNT + "=?",new String[]{account});
        if (updateConut <= 0){//没有更到任何记录在插入
            getContentResolver().insert(ContactsProvider.URI_CONTACT,values);
        }
    }

    public   void saveMessage(String sessionAccount, Message msg){
        ContentValues values = new ContentValues();
        values.put(SmsOpenHelper.SmsTable.FROM_ACCOUNT,StringUtils.substringBefore(msg.getFrom().toString(),"/"));
        values.put(SmsOpenHelper.SmsTable.TO_ACCOUNT,StringUtils.substringBefore(msg.getTo().toString(),"/"));//分割取前段
        values.put(SmsOpenHelper.SmsTable.BODY,msg.getBody());
        values.put(SmsOpenHelper.SmsTable.STATUS,"offline");
        values.put(SmsOpenHelper.SmsTable.TYPE,msg.getType().name());
        values.put(SmsOpenHelper.SmsTable.TIME,System.currentTimeMillis());
        values.put(SmsOpenHelper.SmsTable.SESSION_ACCOUNT, sessionAccount);
        getContentResolver().insert(SmsProvider.URI_SMS,values);
    }

    public  class InChatMessageListener implements IncomingChatMessageListener{
            @Override
            public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
                System.out.println("=======新消息 " + from + ": " + message.getBody()+"| "+message.getType()+
                        "| "+message.getFrom()+"| "+message.getTo()+"|"+chat.getXmppAddressOfChatPartner());
                //保存消息
                saveMessage(from.toString(),message);


            }
        };

}
